package com.gxuwz.weather;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.json.JSONObject;
import java.io.IOException;

public class MoreActivity extends AppCompatActivity implements View.OnClickListener {

    TextView versionTv;
    ImageView backIv;
    private String newVersionUrl;
    private String newVersionName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_more);

        backIv = findViewById(R.id.search_iv_back);
        versionTv = findViewById(R.id.more_tv_version);

        backIv.setOnClickListener(this);
        versionTv.setOnClickListener(this);

        String versionName = getVersionName();
        versionTv.setText("当前版本:    v" + versionName);

        // 检查新版本信息
        checkNewVersion(versionName);
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.search_iv_back:
                intent.setClass(this, MainActivity.class);
                break;
            case R.id.more_tv_version:
                if (newVersionUrl != null && !newVersionUrl.isEmpty()) {
                    // 开始下载新版本
                    startDownload(newVersionUrl);
                } else {
                    Toast.makeText(this, "当前已是最新版本", Toast.LENGTH_SHORT).show();
                }
                break;
        }
        startActivity(intent);
    }

    public String getVersionName() {
        /* 获取应用的版本名称*/
        PackageManager manager = getPackageManager();
        String versionName = null;

        try {
            PackageInfo info = manager.getPackageInfo(getPackageName(), 0);
            versionName = info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionName;
    }

    private void checkNewVersion(String currentVersion) {
        new Thread(() -> {
            OkHttpClient client = new OkHttpClient();
            // 假设这是服务器端提供的获取版本信息的 API
            Request request = new Request.Builder()
                    // 替换成相应的服务器地址
                    .url("http://your-server.com/check_version.php")
                    .build();
            try {
                Response response = client.newCall(request).execute();
                if (response.isSuccessful() && response.body() != null) {
                    String responseData = response.body().string();
                    JSONObject jsonObject = new JSONObject(responseData);
                    newVersionName = jsonObject.getString("version");
                    newVersionUrl = jsonObject.getString("download_url");
                    if (!newVersionName.equals(currentVersion)) {
                        new Handler(Looper.getMainLooper()).post(() -> {
                            Toast.makeText(MoreActivity.this, "发现新版本: " + newVersionName, Toast.LENGTH_SHORT).show();
                        });
                    }
                }
            } catch (IOException | org.json.JSONException e) {
                e.printStackTrace();
            }
        }).start();
    }

    private void startDownload(String url) {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                requestStoragePermission();
            } else {
                android.app.DownloadManager downloadManager = (android.app.DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                android.net.Uri uri = android.net.Uri.parse(url);
                android.app.DownloadManager.Request request = new android.app.DownloadManager.Request(uri);
                request.setNotificationVisibility(android.app.DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                request.setDestinationInExternalPublicDir(android.os.Environment.DIRECTORY_DOWNLOADS, "weather_app_new_version.apk");
                long downloadId = downloadManager.enqueue(request);
            }
        } else {
            android.app.DownloadManager downloadManager = (android.app.DownloadManager) getSystemService(DOWNLOAD_SERVICE);
            android.net.Uri uri = android.net.Uri.parse(url);
            android.app.DownloadManager.Request request = new android.app.DownloadManager.Request(uri);
            request.setNotificationVisibility(android.app.DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
            request.setDestinationInExternalPublicDir(android.os.Environment.DIRECTORY_DOWNLOADS, "weather_app_new_version.apk");
            long downloadId = downloadManager.enqueue(request);
        }
    }

    private static final int PERMISSION_REQUEST_CODE = 1;

    private void requestStoragePermission() {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限已授予，可以开始下载
                if (newVersionUrl != null && !newVersionUrl.isEmpty()) {
                    startDownload(newVersionUrl);
                }
            } else {
                Toast.makeText(this, "需要存储权限才能下载新版本", Toast.LENGTH_SHORT).show();
            }
        }
    }
}